package com.security.control.core.authentication;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.social.security.SocialUserDetailsService;

import javax.sql.DataSource;

/**
 * @author imoot@gamil.com
 * @date 2019/1/15 0015 9:46
 * 认证相关的扩展点配置。只要是配置在这里的bean，业务系统都可以通过声明同类型或同名的bean来覆盖安全模块默认的配置
 */
@Configuration
public class AuthenticationBeanConfig {

    @Autowired
    private DataSource dataSource;

    /**
     * 默认的密码处理器
     */
    @Bean
    @ConditionalOnMissingBean(PasswordEncoder.class)
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    /**
     * 默认的正常用户信息处理服务类
     */
    @Bean
    @ConditionalOnMissingBean(UserDetailsService.class)
    public UserDetailsService userDetailsService(){
        return new DefaultUserDetalisService();
    }

    /**
     * 默认的三方登录用户信息处理服务类
     */
    @Bean
    @ConditionalOnMissingBean(SocialUserDetailsService.class)
    public SocialUserDetailsService socialUserDetailsService(){
        return new DefaultSocialUserDetailsService();
    }

    /**
     * 记住我功能的token存取器
     */
    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
        tokenRepository.setDataSource(dataSource);//设置数据源
        //tokenRepository.setCreateTableOnStartup(true);//启动时创建表
        return tokenRepository;
    }
}
